const router = require("express").Router();
const cors = require("cors");
// const proxy = require("http-proxy-middleware");

const { getAllShop, addShop } = require("../controller/shop");
const { register, login, isLogin, unLogin } = require("../controller/user");

router.get("/shop/list", getAllShop);
router.get("/shop/add", addShop);

router.post("/user/register", register);
router.post("/user/login", login);
router.get("/user/isLogin", isLogin);
router.get("/user/unLogin", unLogin);

// ------cors跨域demo---------
// 给某个单独路由设置cors，还可以配置允许来自某个源的跨域
const option = {
  origin: "http://127.0.0.1:5500"
};
router.get("/demo", cors(option), (req, resp) => {
  resp.json({
    code: 200,
    body: {
      msg: "hello cors"
    }
  });
});
// ------cors跨域demo---------

// ------proxy跨域demo---------
// var options = {
//   target: "https://apiv2.pinduoduo.com", // target host
//   changeOrigin: true, // needed for virtual hosted sites
//   ws: true, // proxy websockets
//   pathRewrite: {
//     "api/gindex/abc": "/api/gindex/subject/limited/goods" // rewrite path
//   },
//   router: {
//     // when request.headers.host == 'dev.localhost:3000',
//     // override target 'http://www.example.org' to 'http://localhost:8000'
//     "dev.localhost:3000": "http://localhost:8000"
//   }
// };
// router.get("/gindex/abc", proxy(options));
// ------proxy跨域demo---------

// --------上传文件demo--------
const formidable = require("formidable");
const path = require("path");
router.post("/upload", (req, resp) => {
  var form = new formidable.IncomingForm();
  // 设置图片存储路径
  form.uploadDir = path.resolve(__dirname, "../public/images");
  // 保留后缀名
  form.keepExtensions = true;
  form.parse(req, function(err, fields, files) {
    if (err) throw err;
    else {
      const imgPath = files.img.path;
      // 从完整路径里取到文件名
      const { base } = path.parse(imgPath);
      const src = "/images/" + base;
      // console.log(src);
      resp.json({
        code: 200,
        body: {
          src
        }
      });
    }
  });
});

// --------上传文件demo--------

module.exports = router;
